package com.xmjs.baselibrary.network.Interceptor;

import android.text.TextUtils;

import com.xmjs.baselibrary.utils.LocalCache;
import com.xmjs.baselibrary.utils.SP;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求拦截器
 */
public class RequestInterceptor implements Interceptor {
    private final SP mSP;

    public RequestInterceptor(SP SP) {
        mSP = SP;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        //头部添加"登录令牌"公共参数
        builder.addHeader("Authorization", "Bearer " + LocalCache.getToken(mSP));
        Request request = chain.request();
        if (request.body() instanceof FormBody) {//表单请求
            FormBody.Builder newFormBody = new FormBody.Builder();//定义新的请求体
            FormBody oldFormBody = (FormBody) request.body(); //获取旧的请求体
            for (int i = 0; i < oldFormBody.size(); i++) {
                String key = oldFormBody.encodedName(i);
                String value = oldFormBody.encodedValue(i);
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                    newFormBody.addEncoded(key, value);
                }
            }
            //请求体添加"时间戳"公共参数
            newFormBody.addEncoded("timestamp", System.currentTimeMillis() + "");
            //把新的请求体添加到请求当中
            builder.method(request.method(), newFormBody.build());
        } else {//url请求
            HttpUrl httpUrl = request.url()
                    .newBuilder()
                    //请求路径添加"时间戳"公共参数
                    .addQueryParameter("timestamp", System.currentTimeMillis() + "")
                    .build();
            builder.url(httpUrl);
        }
        return chain.proceed(builder.build());
    }

}
